{% extends 'pc/base.html' %}
{% load static %}
{% block title %}
    新增文章{{ seo_list.title }}
{% endblock %}
{% block keywords %}
    {{ seo_list.keywords }}
{% endblock %}
{% block desc %}
    {{ seo_list.desc }}
{% endblock %}
{% block css %}
    <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
    <link rel="stylesheet" href="{% static 'css/article_add.css' %}">
    <link rel="stylesheet" href="{% static 'markdown/css/editormd.css' %}"/>
    <style>
        pre span {
            display: initial !important;
        }

        .loading {
            position: absolute;
            top: 50%;
            left: 50%;
            z-index: 999;
        }
    </style>
{% endblock %}
{% block link_js %}
    <script src="{% static 'markdown/editormd.js' %}"></script>
{% endblock %}
{% block content %}
    <section class="main">
        <h4>发布文章</h4>
        <form>
            <div class="form-group">
                <label>标题</label>
                <input type="text" class="form-control validate" name="title" maxlength="100"
                       placeholder="请输入文章标题-不超过100字">
            </div>
            <div class="form-group">
                <label>关键字(Keywords)</label>
                <input type="text" class="form-control" name="keywords" maxlength="200"
                       placeholder="请输入关键字，以英文逗号分割，利于搜索引擎收录-不超过200字">
            </div>
            <div class="form-group">
                <label>描述(Description)</label>
                <input type="text" class="form-control" maxlength="256" name="desc" placeholder="请输入文章描述-不超过256字">
            </div>
            <div class="form-group">
                <label>列表图(List_pic)</label>
                <div class="file">
                    <div class="file_style">
                        <span></span>
                        <input type="file" id="file" name="list_pic" accept="image/*">
                    </div>
                    <p class="img"><i class="glyphicon glyphicon-remove" style="color: #f5f5f5;"></i></p>

                </div>

            </div>
            <div class="form-group">
                <label>文章内容</label>
                <div id="test-editormd">
                    <textarea name="" class="form-control"></textarea>
                </div>
            </div>
            <div class="form-group">
                <label>选择文章分类</label>
                <select name="category" class="form-control">
                    <option value="">--请选择--</option>
                    {% for foo in category %}
                        <option value="{{ foo.id }}">{{ foo.name }}</option>
                    {% endfor %}

                </select>
            </div>
            <button type="button" class="btn btn-default" id="btn">文章发布</button>
        </form>
    </section>
{% endblock %}
{% block js %}

    <script>
        document.getElementById('test-editormd').addEventListener('paste', function (e) {
            if (!(e.clipboardData && e.clipboardData.items)) {
                return;
            }
            for (var i = 0, len = e.clipboardData.items.length; i < len; i++) {
                var item = e.clipboardData.items[i];
                if (item.kind === "string") {
                    item.getAsString(function (str) {
                        //console.log(str);
                    })
                } else if (item.kind === "file") {
                    var f = item.getAsFile();
                    let form = new FormData()
                    form.append('editormd-image-file', f)
                    $.ajax({
                        contentType: false,
                        processData: false,
                        url: '/article/blog_img_upload/',
                        type: 'post',
                        data: form,
                        beforeSend: function () {
                            $("body").append("<p class='loading'><img src='/static/img/5-121204193R5-50.gif'></p>")
                        },
                        success: function (res) {
                            $('.loading').remove()
                            if (res.success == 1) testEditor.insertValue("![](" + res.url + ")");
                        },
                        error: function (err) {
                            $('.loading').remove()
                            console.log(err)
                        }
                    })
                }
            }
        });

        var testEditor;
        $(function () {
            testEditor = editormd("test-editormd", {
                width: "100%",
                height: 800,
                syncScrolling: "single",
                path: "/static/markdown/lib/",
                flowChart: true,
                saveHTMLToTextarea: true,//注意3：这个配置，textarea可以提交
                emoji: true,//emoji表情，默认关闭
                /**上传图片相关配置如下*/
                imageUpload: true,
                imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
                imageUploadURL: "/article/blog_img_upload/",
            });

        });

        function validate(obj, el) {
            if (!obj || obj.trim() == "") {
                el.css('border-color', 'red');
                return false;
            } else {
                return true
            }
        }

        $("#btn").on('click', function () {
            if (validate($('.validate').val(), $('.validate')) && validate($('select').val(), $('select')) && validate(testEditor.getMarkdown(), $('#test-editormd'))) {
                $("#btn").attr('disabled', true)
                var title = $("input[name='title']").val();
                var desc = $("input[name='desc']").val();
                var keywords = $("input[name='keywords']").val();
                var list_pic = $("input[name='list_pic']")[0].files[0];
                var category = $("select[name='category']").val();
                var form = new FormData()
                form.append('authors', '{{ request.user.id }}')
                form.append('title', title)
                form.append('desc', desc)
                form.append('keywords', keywords)
                form.append('list_pic', list_pic)
                form.append('content', testEditor.getMarkdown())
                form.append('csrfmiddlewaretoken', '{{ csrf_token }}')
                form.append('category', category)
                $.ajax({
                    url: '/article/created/',
                    type: 'post',
                    contentType: false,
                    data: form,
                    processData: false,
                    success: function (data) {
                        if (data.code == 200) {
                            window.location.href = '{% url 'home' %}'
                        } else {
                            swal({
                                text: data.data,
                                icon: "error",
                            })
                            $("#btn").attr('disabled', false)
                        }
                    },
                    error: function (xhr) {
                        console.log(xhr)
                    }
                })
            }


        })
        $('#file').on('change', function () {
            var read = new FileReader() // 创建FileReader对像;
            read.readAsDataURL(this.files[0])  // 调用readAsDataURL方法读取文件;
            read.onload = function () {
                url = read.result  // 拿到读取结果;
                var img = new Image();
                img.src = url;
                $(".img").show()
                $(".img").append(img)
                $('.file_style').hide()
            }

            /*$.ajax({
                url:'/cms/uplpad_file/',
                type:'post',
                processData:false,
                contentType:false,
                data:form,
                headers:{'X-CSRFToken':$.cookie('csrftoken')},
                success:function (data) {
                    $("#input_file").val(data.data)
                    console.log(data)
                }
            })*/
        })
        $('.img i').on('click', function () {
            $(this).parent().find('img').remove();
            $('#file').val('');
            $(this).parent().hide();
            $('.file_style').show();
        })
    </script>
{% endblock %}